<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rust代码分析 - Rust知识解释智能体</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@11.8.0/styles/github.min.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            min-height: 100vh;
            background: #f5f6fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .layout {
            display: flex;
            min-height: 100vh;
        }
        .sidebar {
            width: 420px;
            background: #fff;
            border-radius: 0 18px 18px 0;
            box-shadow: 2px 0 16px rgba(52,152,219,0.08);
            padding: 32px 24px 24px 24px;
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            z-index: 2;
        }
        .sidebar h3 {
            margin-top: 0;
            color: #222;
            font-size: 1.2rem;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .sidebar .task-list {
            margin-top: 24px;
            width: 100%;
            overflow-y: auto;
            flex: 1;
        }
        .sidebar .task-list::-webkit-scrollbar {
            width: 6px;
            background: #f0f0f0;
        }
        .sidebar .task-list::-webkit-scrollbar-thumb {
            background: #e0e6ed;
            border-radius: 3px;
        }
        .main-content {
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: flex-start;
            padding: 48px 0;
        }
        .editor-card {
            background: #fff;
            border-radius: 18px;
            box-shadow: 0 4px 24px rgba(52,152,219,0.10);
            padding: 48px 60px 36px 36px; /* 缩小padding */
            max-width: 1100px; /* 缩小最大宽度 */
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            margin: auto; /* 居中 */
        }
        .editor-title {
            font-size: 1.3rem;
            color: #222;
            font-weight: bold;
            margin-bottom: 0;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .blue-underline {
            width: 200px;
            height: 4px;
            background: #4f8cff;
            border-radius: 2px;
            margin: 10px 0 24px 0;
        }
        #monaco-editor {
            width: 100%;
            min-height: 400px;
            max-height:50vh;
            border-radius: 10px;
            border: 1.5px solid #e0e6ed;
            box-shadow: 0 2px 8px rgba(52,152,219,0.08);
            margin-bottom: 24px;
            background: #181c24;
            max-width: 1300px; /* 提高最大宽度 */
        }
        .button-group {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 18px;
            margin-bottom: 18px;
            width: 100%;
            max-width: 1300px; /* 提高最大宽度 */
        }
        .submit-btn, .run-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
            color: #fff;
            border: none;
            border-radius: 12px;
            padding: 14px 32px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            margin: 0;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            letter-spacing: 0.3px;
            position: relative;
            overflow: hidden;
        }
        .submit-btn::before, .run-btn::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.3);
            transform: translate(-50%, -50%);
            transition: width 0.6s, height 0.6s;
        }
        .submit-btn:hover, .run-btn:hover {
            background: linear-gradient(135deg, #764ba2 0%, #667eea 50%, #f093fb 100%);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
            transform: translateY(-2px);
        }
        .submit-btn:hover::before, .run-btn:hover::before {
            width: 300px;
            height: 300px;
        }
        .submit-btn:active, .run-btn:active {
            transform: translateY(0);
            box-shadow: 0 2px 10px rgba(102, 126, 234, 0.4);
        }
        .submit-btn i, .run-btn i {
            font-size: 1.1rem;
            transition: transform 0.3s ease;
        }
        .submit-btn:hover i, .run-btn:hover i {
            transform: scale(1.1);
        }
        .run-result {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 12px 10px;
            min-height: 40px;
            font-size: 0.98rem;
            color: #222;
            box-shadow: 0 2px 8px rgba(0,0,0,0.04);
            white-space: pre-wrap;
            word-break: break-all;
            width: 100%;
            margin-bottom: 0;
        }
        
        .analysis-result {
            background: transparent;
            border: none;
            border-radius: 0;
            padding: 0;
            min-height: 40px;
            font-size: 0.98rem;
            color: #222;
            box-shadow: none;
            white-space: normal;
            word-break: normal;
            width: 100%;
            margin-bottom: 0;
        }
        
        /* 分析结果美化样式 */
        .analysis-main-card {
            transition: all 0.3s ease;
        }
        
        .analysis-main-card:hover {
            box-shadow: 0 6px 24px rgba(79, 140, 255, 0.12) !important;
        }
        
        .analysis-section-item {
            transition: all 0.2s ease;
        }
        
        .analysis-section-item:hover {
            background: linear-gradient(90deg, rgba(102, 126, 234, 0.02) 0%, transparent 100%);
            border-radius: 8px;
            padding: 8px;
            margin: -8px;
        }
        
        .analysis-main-card pre {
            background: #f8f9fa !important;
            border: 1px solid #e0e6ed;
            border-radius: 6px;
            padding: 14px 16px;
            overflow-x: auto;
            margin: 12px 0;
        }
        
        .analysis-main-card pre code {
            background: transparent !important;
            padding: 0;
            font-size: 0.9rem;
            line-height: 1.6;
        }
        
        .analysis-main-card ol,
        .analysis-main-card ul {
            margin: 10px 0 10px 24px;
            padding-left: 20px;
        }
        
        .analysis-main-card ol ol,
        .analysis-main-card ul ul {
            margin: 6px 0 6px 20px;
            padding-left: 20px;
        }
        
        .analysis-main-card li {
            margin: 8px 0;
            line-height: 1.75;
            color: #555;
        }
        
        .analysis-main-card li::marker {
            color: #667eea;
            font-weight: 600;
        }
        
        .analysis-main-card p {
            margin: 12px 0;
            line-height: 1.85;
            color: #444;
        }
        
        .analysis-main-card h4,
        .analysis-main-card h5 {
            margin: 16px 0 10px 0;
            color: #333;
            font-weight: 600;
        }
        
        .analysis-main-card strong {
            color: #495057;
            font-weight: 600;
        }
        
        .analysis-main-card code:not(pre code) {
            background: #f1f3f5;
            color: #e83e8c;
            padding: 3px 6px;
            border-radius: 4px;
            font-size: 0.9em;
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            border: 1px solid #e9ecef;
        }
        
        /* 层级编号样式（3.1, 3.2等） */
        .analysis-main-card .analysis-section-content {
            position: relative;
        }
        
        .analysis-main-card .analysis-section-content > *:first-child {
            margin-top: 0;
        }
        
        .analysis-main-card .analysis-section-content > *:last-child {
            margin-bottom: 0;
        }
        @media (max-width: 1000px) {
            .sidebar { display: none; }
            .main-content { padding: 12px 0; }
            .editor-card { max-width: 98vw; padding: 16px 4vw; }
        }
        @media (max-width: 600px) {
            .editor-title { font-size: 1.05rem; }
            .blue-underline { width: 120px; }
            .editor-card { padding: 8px 2vw; }
        }
        
        /* intelligent_practice.css */
        .practice-container {
            width: 100%;
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .controls {
            display: flex;
            flex-direction: column;
            gap: 20px;
            margin-bottom: 20px;
            align-items: stretch;
        }

        .control-group {
            display: flex;
            flex-direction: column;
        }

        .control-group label {
            margin-bottom: 5px;
            font-weight: bold;
            color: #333;
        }

        .control-group select {
            padding: 8px 12px;
            border-radius: 4px;
            border: 1px solid #ccc;
            font-size: 16px;
        }

        .button-group-controls {
            display: flex;
            gap: 12px;
            align-items: flex-start;
            flex-wrap: wrap;
        }

        .action-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #fff;
            border: none;
            border-radius: 10px;
            padding: 12px 24px;
            font-size: 0.95rem;
            font-weight: 600;
            cursor: pointer;
            box-shadow: 0 3px 12px rgba(102, 126, 234, 0.35);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            letter-spacing: 0.3px;
            position: relative;
            overflow: hidden;
            align-self: flex-start;
        }
        .action-btn::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.25);
            transform: translate(-50%, -50%);
            transition: width 0.5s, height 0.5s;
        }
        .action-btn:hover {
            background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
            box-shadow: 0 5px 18px rgba(102, 126, 234, 0.5);
            transform: translateY(-2px);
        }
        .action-btn:hover::before {
            width: 250px;
            height: 250px;
        }
        .action-btn:active {
            transform: translateY(0);
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.4);
        }
        .action-btn i {
            font-size: 1rem;
            transition: transform 0.3s ease;
        }
        .action-btn:hover i {
            transform: scale(1.15) rotate(5deg);
        }
        .action-btn:disabled {
            background: linear-gradient(135deg, #cccccc 0%, #999999 100%);
            cursor: not-allowed;
            box-shadow: none;
            opacity: 0.6;
        }
        .action-btn:disabled:hover {
            transform: none;
            box-shadow: none;
        }
        
        /* 生成题目按钮特殊样式 */
        #generate-btn {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 50%, #4facfe 100%);
            background-size: 200% 200%;
            color: #fff;
            border: none;
            border-radius: 12px;
            padding: 14px 32px;
            font-size: 1rem;
            font-weight: 700;
            cursor: pointer;
            box-shadow: 0 4px 20px rgba(245, 87, 108, 0.4), 0 0 0 0 rgba(245, 87, 108, 0.7);
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            letter-spacing: 0.5px;
            position: relative;
            overflow: hidden;
            align-self: flex-start;
            animation: gradientShift 3s ease infinite;
        }
        @keyframes gradientShift {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }
        #generate-btn::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.4);
            transform: translate(-50%, -50%);
            transition: width 0.6s, height 0.6s;
        }
        #generate-btn::after {
            content: '';
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.1), transparent);
            transform: rotate(45deg);
            animation: shine 3s infinite;
        }
        @keyframes shine {
            0% { transform: translateX(-100%) translateY(-100%) rotate(45deg); }
            100% { transform: translateX(100%) translateY(100%) rotate(45deg); }
        }
        #generate-btn:hover {
            background: linear-gradient(135deg, #4facfe 0%, #f5576c 50%, #f093fb 100%);
            box-shadow: 0 6px 25px rgba(245, 87, 108, 0.6), 0 0 0 8px rgba(245, 87, 108, 0.1);
            transform: translateY(-3px) scale(1.05);
            animation: none;
            background-position: 100% 50%;
        }
        #generate-btn:hover::before {
            width: 300px;
            height: 300px;
        }
        #generate-btn:active {
            transform: translateY(-1px) scale(1.02);
            box-shadow: 0 3px 15px rgba(245, 87, 108, 0.5);
        }
        #generate-btn i {
            font-size: 1.2rem;
            transition: transform 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55);
            animation: rotateIcon 2s ease-in-out infinite;
        }
        @keyframes rotateIcon {
            0%, 100% { transform: rotate(0deg); }
            25% { transform: rotate(-10deg); }
            75% { transform: rotate(10deg); }
        }
        #generate-btn:hover i {
            transform: rotate(360deg) scale(1.2);
            animation: none;
        }
        #generate-btn:disabled {
            background: linear-gradient(135deg, #cccccc 0%, #999999 100%);
            cursor: not-allowed;
            box-shadow: none;
            opacity: 0.6;
            animation: none;
        }
        #generate-btn:disabled:hover {
            transform: none;
            box-shadow: none;
        }
        #generate-btn:disabled i {
            animation: none;
        }
        #generate-btn.loading {
            pointer-events: none;
            opacity: 0.8;
        }
        #generate-btn.loading i {
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }

        .question-area {
            margin-top: 20px;
        }

        .question-content {
            padding: 20px;
            background-color: #f9f9f9;
            border: 1px solid #eee;
            border-radius: 4px;
            min-height: 100px;
        }

        .knowledge-points-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            padding: 10px 0;
        }

        .knowledge-point-tag {
            background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);
            border: 2px solid #dee2e6;
            border-radius: 25px;
            padding: 10px 18px;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            font-size: 14px;
            font-weight: 500;
            color: #495057;
            position: relative;
            overflow: hidden;
        }
        .knowledge-point-tag::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            border-radius: 50%;
            background: rgba(102, 126, 234, 0.1);
            transform: translate(-50%, -50%);
            transition: width 0.4s, height 0.4s;
        }
        .knowledge-point-tag:hover {
            background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
            border-color: #667eea;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
        }
        .knowledge-point-tag:hover::before {
            width: 150px;
            height: 150px;
        }

        .knowledge-point-tag.selected {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-color: #667eea;
            box-shadow: 0 3px 10px rgba(102, 126, 234, 0.4);
            transform: scale(1.05);
        }
        
        /* 返回按钮样式 */
        .back-btn {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: #fff;
            border: none;
            border-radius: 10px;
            padding: 10px 20px;
            font-size: 0.95rem;
            font-weight: 600;
            cursor: pointer;
            box-shadow: 0 3px 12px rgba(79, 172, 254, 0.35);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            letter-spacing: 0.3px;
            position: relative;
            overflow: hidden;
        }
        .back-btn::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.3);
            transform: translate(-50%, -50%);
            transition: width 0.5s, height 0.5s;
        }
        .back-btn:hover {
            background: linear-gradient(135deg, #00f2fe 0%, #4facfe 100%);
            box-shadow: 0 5px 18px rgba(79, 172, 254, 0.5);
            transform: translateY(-2px) translateX(-3px);
        }
        .back-btn:hover::before {
            width: 250px;
            height: 250px;
        }
        .back-btn:active {
            transform: translateY(0) translateX(0);
            box-shadow: 0 2px 8px rgba(79, 172, 254, 0.4);
        }
        .back-btn i {
            font-size: 0.9rem;
            transition: transform 0.3s ease;
        }
        .back-btn:hover i {
            transform: translateX(-3px);
        }
    </style>
    <script src="https://unpkg.com/monaco-editor@0.34.1/min/vs/loader.js"></script>
    <script src="https://unpkg.com/mermaid@10.9.0/dist/mermaid.min.js"></script>
</head>
<body>
    <div class="layout">
        
        <div class="main-content">
            <button id="backBtn" onclick="window.location.href='/dashboard'" class="back-btn" style="margin-bottom: 18px;">
                <i class="fas fa-arrow-left"></i> 返回问答界面
            </button>
            <div class="editor-card">
                <div class="practice-container">
                    <div class="controls">
                        <div class="control-group">
                            <label><i class="fas fa-book"></i> 知识点 (可多选)</label>
                            <div id="knowledge-points" class="knowledge-points-container">
                                <span class="knowledge-point-tag" data-value="variable_declaration">变量声明</span>
                                <span class="knowledge-point-tag" data-value="mutable_variables">可变变量</span>
                                <span class="knowledge-point-tag" data-value="function_definition">函数定义</span>
                                <span class="knowledge-point-tag" data-value="data_types">数据类型</span>
                                <span class="knowledge-point-tag" data-value="ownership">所有权</span>
                                <span class="knowledge-point-tag" data-value="borrowing">借用</span>
                                <span class="knowledge-point-tag" data-value="structs">结构体</span>
                                <span class="knowledge-point-tag" data-value="enums">枚举</span>
                                <span class="knowledge-point-tag" data-value="pattern_matching">模式匹配</span>
                                <span class="knowledge-point-tag" data-value="traits">Trait</span>
                                <span class="knowledge-point-tag" data-value="generics">泛型</span>
                                <span class="knowledge-point-tag" data-value="lifetimes">生命周期</span>
                                <span class="knowledge-point-tag" data-value="closures">闭包</span>
                                <span class="knowledge-point-tag" data-value="iterators">迭代器</span>
                                <span class="knowledge-point-tag" data-value="smart_pointers">智能指针</span>
                                <span class="knowledge-point-tag" data-value="multithreading">多线程</span>
                                <span class="knowledge-point-tag" data-value="macros">宏</span>
                            </div>
                        </div>
                        <div class="control-group">
                            <label for="difficulty"><i class="fas fa-signal"></i> 难度</label>
                            <select id="difficulty">
                                <option value="easy">简单</option>
                                <option value="medium">中等</option>
                                <option value="hard">困难</option>
                            </select>
                        </div>
                        <div class="button-group-controls">
                            <button id="generate-btn"><i class="fas fa-cogs"></i> 生成题目</button>
                            <button id="view-solution-btn" class="action-btn" style="display: none;"><i class="fas fa-eye"></i> 查看解析</button>
                        </div>
                    </div>
                    <div class="question-area">
                        <h3>题目</h3>
                        <div id="question-content" class="question-content">
                            <p>请在这里查看生成的题目。</p>
                        </div>
                        <div id="solution-content" class="question-content" style="display: none; margin-top: 10px;">
                            <h4>答案与解析</h4>
                            <p id="solution-text"></p>
                        </div>
                    </div>
                </div>

                <div class="editor-title">
                    <i class="fas fa-code"></i> Rust 代码分析与在线运行
                </div>
                <div class="blue-underline"></div>
                <div id="monaco-editor"></div>
                <div class="button-group">
                    <button type="button" class="run-btn" id="runRustBtn"><i class="fas fa-play"></i> 运行</button>
                    <button type="button" class="submit-btn" id="analyzeBtn"><i class="fas fa-paper-plane"></i> 提交分析</button>
                </div>
                <div id="runResult" class="run-result" style="display:none;"></div>
                <div id="analysisResult" class="analysis-result">分析结果将在此处展示</div>
            </div>
        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/js/all.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/highlight.js@11.8.0/highlight.min.js"></script>
    <script>
    let monacoEditor;
    require.config({ paths: { 'vs': 'https://unpkg.com/monaco-editor@0.34.1/min/vs' }});
    require(['vs/editor/editor.main'], function() {
        monacoEditor = monaco.editor.create(document.getElementById('monaco-editor'), {
            value: '// 在此输入您的Rust代码\nfn main() {\n    println!(\"Hello, Rust!\");\n}',
            language: 'rust',
            theme: 'vs-dark',
            fontSize: 16,
            minimap: { enabled: false },
            automaticLayout: true
        });
        
    });
    
    // 运行按钮事件
    document.addEventListener('DOMContentLoaded', function() {
        const runBtn = document.getElementById('runRustBtn');
        const runResultDiv = document.getElementById('runResult');
        if (runBtn) {
            runBtn.addEventListener('click', async function() {
                runResultDiv.style.display = 'block';
                runResultDiv.innerHTML = '<div style=\'font-weight:bold;color:#fff;background:#222;padding:6px 12px 4px 12px;border-radius:8px 8px 0 0;font-size:1rem;\'>运行结果</div>' +
                  '<pre id=\'runResultBox\' style=\'background:#181c24;color:#e8eaf6;padding:16px 14px 14px 14px;border-radius:0 0 8px 8px;margin:0;font-size:1.05rem;overflow-x:auto;\'>正在运行...</pre>';
                const code = monacoEditor.getValue();
                try {
                    const resp = await fetch('/api/run_rust_code', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ code })
                    });
                    const data = await resp.json();
                    const resultBox = document.getElementById('runResultBox');
                    if (data.status === 'success') {
                        resultBox.textContent = (data.stdout && data.stdout.trim() ? data.stdout : '[无输出]') + (data.stderr ? ('\n[stderr]\n' + data.stderr) : '');
                    } else {
                        resultBox.textContent = (data.message || '运行失败') + (data.stderr ? ('\n' + data.stderr) : '');
                    }
                } catch (e) {
                    const resultBox = document.getElementById('runResultBox');
                    resultBox.textContent = '运行出错: ' + e;
                }
            });
        }
    });
    // 分析按钮事件
    document.getElementById('analyzeBtn').onclick = async function() {
        const analysisDiv = document.getElementById('analysisResult');
        analysisDiv.innerHTML = '<span style="color:#888;">正在分析，请稍候...</span>';
        const code = monacoEditor.getValue();
        let examples = localStorage.getItem('rust_examples');
        // 获取题目内容（从code_practice界面）
        const questionContent = document.getElementById('question-content');
        let questionText = '';
        if (questionContent) {
            // 提取纯文本内容，去除HTML标签
            questionText = questionContent.innerText || questionContent.textContent || '';
            questionText = questionText.trim();
            // 如果题目内容包含"请在这里查看生成的题目"等提示文本，则认为是空题目
            if (questionText.includes('请在这里查看生成的题目') || questionText.includes('正在为知识点')) {
                questionText = '';
            }
        }
        try {
            const resp = await fetch('/api/analyze_rust_code', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ code, examples, question: questionText })
            });
            const data = await resp.json();
            if (data.status === 'success') {
                let result = data.result || '';
                // 每一块用小卡片包裹，显示：1. 正确性分析、2. 代码改进建议、3. 下一步练习建议（包含3.1、3.2）、4. 正向反馈
                function beautifyAnalysisSections(md) {
                    // 优化分块正则，支持层级编号（如 3.1, 3.2）
                    // 支持：### 1.、### 1.1、1. 、1.1.、等格式
                    const sectionRegex = /^(###|####)?\s*(\d+(?:\.\d+)*)[\.、]\s*[^\n]*$/gm;
                    let indices = [];
                    let match;
                    while ((match = sectionRegex.exec(md)) !== null) {
                        const level = (match[2].match(/\./g) || []).length; // 计算层级深度（.的个数）
                        indices.push({ 
                            idx: match.index, 
                            title: match[0], 
                            number: match[2], 
                            level: level 
                        });
                    }
                    // 收集所有主项（level 0）的内容
                    // 特殊处理：如果遇到"下一步练习建议"主项，跳过它，但将其子项提升为独立主项
                    let sections = [];
                    let skipNextPracticeIndex = -1; // 记录"下一步练习建议"的索引
                    
                    // 第一遍：找到"下一步练习建议"的索引
                    for (let i = 0; i < indices.length; i++) {
                        if (indices[i].level === 0) {
                            const titleText = indices[i].title.replace(/^(###|####)?\s*/, '').trim();
                            const mainTitleText = titleText.replace(/^\d+[\.、]\s*/, '')
                                .replace(/\*\*/g, '')
                                .replace(/__/g, '')
                                .trim();
                            if (mainTitleText.includes('下一步练习建议')) {
                                skipNextPracticeIndex = i;
                                break;
                            }
                        }
                    }
                    
                    // 找到"下一步练习建议"之后的下一个level 0主项的索引
                    let nextMainIndexAfterNextPractice = indices.length;
                    if (skipNextPracticeIndex >= 0) {
                        for (let j = skipNextPracticeIndex + 1; j < indices.length; j++) {
                            if (indices[j].level === 0) {
                                nextMainIndexAfterNextPractice = j;
                                break;
                            }
                        }
                    }
                    
                    // 第二遍：处理所有主项
                    for (let i = 0; i < indices.length; i++) {
                        // 如果是"下一步练习建议"主项，跳过它
                        if (i === skipNextPracticeIndex) {
                            continue;
                        }
                        
                        // 处理"下一步练习建议"的子项（level 1），将它们提升为独立主项
                        if (indices[i].level === 1 && skipNextPracticeIndex >= 0 && 
                            i > skipNextPracticeIndex && i < nextMainIndexAfterNextPractice) {
                            // 这是"下一步练习建议"的子项，将其提升为独立主项
                            let start = indices[i].idx;
                            let end = md.length;
                            
                            // 查找下一个同级或更高级的项目作为结束位置
                            for (let j = i + 1; j < indices.length; j++) {
                                if (indices[j].level <= indices[i].level) {
                                    end = indices[j].idx;
                                    break;
                                }
                            }
                            
                            let sectionMd = md.slice(start, end).trim();
                            let titleLine = indices[i].title;
                            let titleText = titleLine.replace(/^(###|####)?\s*/, '').trim();
                            
                            // 去掉标题行
                            let sectionContentMd = sectionMd;
                            const mainTitlePattern = new RegExp('^' + titleLine.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s*$', 'm');
                            sectionContentMd = sectionContentMd.replace(mainTitlePattern, '').trim();
                            
                            // 提取标题文本（去掉编号和Markdown格式）
                            const mainTitleText = titleText.replace(/^\d+[\.、]\s*/, '')
                                .replace(/\*\*/g, '')
                                .replace(/__/g, '')
                                .trim();
                            
                            // 清理内容中重复的标题
                            const escapedTitle = mainTitleText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
                            const titlePatterns = [
                                new RegExp(`^\\s*\\d+[\.、]\\s*\\*\\*${escapedTitle}\\*\\*\\s*[:：]?\\s*$`, 'gm'),
                                new RegExp(`^\\s*\\d+[\.、]\\s*${escapedTitle}\\s*[:：]?\\s*$`, 'gm'),
                                new RegExp(`^\\s*\\*\\*${escapedTitle}\\*\\*\\s*[:：]?\\s*$`, 'gm'),
                                new RegExp(`^\\s*${escapedTitle}\\s*[:：]?\\s*$`, 'gm'),
                            ];
                            
                            let prevContent = '';
                            while (prevContent !== sectionContentMd) {
                                prevContent = sectionContentMd;
                                for (const pattern of titlePatterns) {
                                    sectionContentMd = sectionContentMd.replace(pattern, '');
                                }
                                sectionContentMd = sectionContentMd.trim();
                            }
                            
                            // 保持原始标题，编号会在最后统一重新编号时处理
                            
                            sectionContentMd = sectionContentMd.replace(/\n{3,}/g, '\n\n').trim();
                            let content = mdToOrderedList(sectionContentMd);
                            
                            sections.push({
                                title: titleText,
                                content: content
                            });
                            continue; // 已处理，跳过后续处理
                        }
                        
                        // 跳过其他子项（level > 0），它们不应该作为独立主项
                        if (indices[i].level > 0) {
                            continue;
                        }
                        
                        // 处理普通主项（level 0）
                        let start = indices[i].idx;
                        let end = md.length;
                        
                        // 查找下一个同级或更高级的项目作为结束位置
                        for (let j = i + 1; j < indices.length; j++) {
                            if (indices[j].level <= indices[i].level) {
                                end = indices[j].idx;
                                break;
                            }
                        }
                        
                        let sectionMd = md.slice(start, end).trim();
                        
                        // 提取标题文本（保留数字和内容）
                        let titleLine = indices[i].title;
                        let titleText = titleLine.replace(/^(###|####)?\s*/, '').trim();
                        
                        // 去掉主项标题行，但保留子项标题（如3.1, 3.2）
                        let sectionContentMd = sectionMd;
                        const mainTitlePattern = new RegExp('^' + titleLine.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s*$', 'm');
                        sectionContentMd = sectionContentMd.replace(mainTitlePattern, '').trim();
                        
                        // 提取标题文本（去掉编号和Markdown格式）
                        const mainTitleText = titleText.replace(/^\d+[\.、]\s*/, '') // 去掉编号部分
                            .replace(/\*\*/g, '') // 去掉加粗标记
                            .replace(/__/g, '') // 去掉下划线标记
                            .trim();
                        
                        // 清理内容中所有重复出现的标题
                        // 转义特殊字符，用于正则表达式
                        const escapedTitle = mainTitleText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
                        
                        // 匹配各种可能的标题格式并删除：
                        // 注意：只删除完全匹配当前主项标题的行，不会误删子项标题
                        const titlePatterns = [
                            // 匹配行首的标题（带任意编号 + 加粗 + 可选冒号）
                            new RegExp(`^\\s*\\d+[\.、]\\s*\\*\\*${escapedTitle}\\*\\*\\s*[:：]?\\s*$`, 'gm'),
                            // 匹配行首的标题（带任意编号，不加粗，可选冒号）
                            new RegExp(`^\\s*\\d+[\.、]\\s*${escapedTitle}\\s*[:：]?\\s*$`, 'gm'),
                            // 匹配行首的标题（只有加粗，无编号，可选冒号）
                            new RegExp(`^\\s*\\*\\*${escapedTitle}\\*\\*\\s*[:：]?\\s*$`, 'gm'),
                            // 匹配行首的标题（无编号，不加粗，可选冒号）
                            new RegExp(`^\\s*${escapedTitle}\\s*[:：]?\\s*$`, 'gm'),
                        ];
                        
                        // 删除所有匹配的标题行（多次执行确保清理彻底）
                        let prevContent = '';
                        while (prevContent !== sectionContentMd) {
                            prevContent = sectionContentMd;
                            for (const pattern of titlePatterns) {
                                sectionContentMd = sectionContentMd.replace(pattern, '');
                            }
                            sectionContentMd = sectionContentMd.trim();
                        }
                        
                        // 清理多余的空白行（3个或更多连续换行变为2个）
                        sectionContentMd = sectionContentMd.replace(/\n{3,}/g, '\n\n').trim();
                        
                        // 处理层级内容：保持层级编号格式（如3.1, 3.2），子项内容会保留在主项中
                        let content = mdToOrderedList(sectionContentMd);
                        
                        sections.push({
                            title: titleText,
                            content: content
                        });
                    }
                    
                    // 对sections进行重新编号，确保编号连续（1, 2, 3, 4, 5）
                    sections = sections.map((section, index) => {
                        const newNumber = index + 1;
                        // 替换标题中的编号（包括层级编号，如"3.1"中的"3.1"应该被替换为"3"）
                        // 匹配开头的数字、点号和可能的子编号
                        const newTitle = section.title.replace(/^\d+(?:\.\d+)*[\.、]\s*/, newNumber + '. ');
                        return {
                            title: newTitle,
                            content: section.content
                        };
                    });
                    
                    // 将所有部分放在一个大卡片中
                    if (sections.length > 0) {
                        let sectionsHtml = sections.map((section, index) => {
                            // 为每个部分添加分隔线（除了最后一个）
                            const separator = index < sections.length - 1 
                                ? '<div style="height:1px;background:linear-gradient(to right, transparent 0%, #e0e6ed 20%, #e0e6ed 80%, transparent 100%);margin:24px 0;position:relative;"><div style="position:absolute;left:50%;top:50%;transform:translate(-50%, -50%);background:#fff;padding:0 12px;color:#999;font-size:0.75rem;">◆</div></div>' 
                                : '';
                            
                            // 根据索引选择不同的颜色（支持5个部分）
                            const colors = [
                                'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                                'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
                                'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
                                'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
                                'linear-gradient(135deg, #fa709a 0%, #fee140 100%)'
                            ];
                            const bgColor = colors[index % colors.length];
                            
                            // 从标题中提取编号（如果存在），用于显示徽章编号
                            // 如果标题格式是 "3. **相关知识点**："，则提取 "3"
                            const titleMatch = section.title.match(/^(\d+)[\.、]/);
                            const sectionNumber = titleMatch ? titleMatch[1] : (index + 1).toString();
                            
                            return `
                                <div class="analysis-section-item" style="margin-bottom:${index < sections.length - 1 ? '0' : '0'}px;">
                                    <div class="analysis-section-title" style="font-weight:700;color:#1976d2;font-size:1.1rem;margin-bottom:14px;padding-bottom:10px;border-bottom:2px solid #e8f4fd;display:flex;align-items:center;gap:10px;">
                                        <span style="display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;background:${bgColor};color:#fff;border-radius:50%;font-size:0.95rem;font-weight:bold;flex-shrink:0;box-shadow:0 2px 8px rgba(102, 126, 234, 0.3);">${sectionNumber}</span>
                                        <span style="flex:1;">${section.title}</span>
                                    </div>
                                    <div class="analysis-section-content" style="color:#444;line-height:1.85;font-size:0.95rem;padding-left:42px;">
                                        ${section.content}
                                    </div>
                                </div>
                                ${separator}
                            `;
                        }).join('');
                        
                        return `<div class="analysis-main-card" style="background:#fff;border-radius:12px;padding:28px 24px;margin-bottom:20px;border:1px solid #e0e6ed;box-shadow:0 4px 16px rgba(79, 140, 255, 0.08);">
                            <div style="display:flex;align-items:center;gap:10px;margin-bottom:24px;padding-bottom:16px;border-bottom:2px solid #f0f4f8;">
                                <div style="width:4px;height:24px;background:linear-gradient(135deg, #667eea 0%, #764ba2 100%);border-radius:2px;"></div>
                                <h3 style="margin:0;font-size:1.2rem;font-weight:700;color:#222;display:flex;align-items:center;gap:8px;">
                                    <i class="fas fa-chart-line" style="color:#667eea;"></i>
                                    代码分析结果
                                </h3>
                            </div>
                            <div class="analysis-sections-container">
                                ${sectionsHtml}
                            </div>
                        </div>`;
                    }
                    
                    // 如果没有找到分块，返回整体渲染
                    let content = mdToOrderedList(md);
                    return `<div class="analysis-main-card" style="background:#fff;border-radius:12px;padding:28px 24px;margin-bottom:20px;border:1px solid #e0e6ed;box-shadow:0 4px 16px rgba(79, 140, 255, 0.08);">
                        <div style="display:flex;align-items:center;gap:10px;margin-bottom:24px;padding-bottom:16px;border-bottom:2px solid #f0f4f8;">
                            <div style="width:4px;height:24px;background:linear-gradient(135deg, #667eea 0%, #764ba2 100%);border-radius:2px;"></div>
                            <h3 style="margin:0;font-size:1.2rem;font-weight:700;color:#222;">代码分析结果</h3>
                        </div>
                        <div class="analysis-section-content" style="color:#333;line-height:1.8;font-size:0.95rem;">
                            ${content}
                        </div>
                    </div>`;
                }
                // 分点转有序列表函数，提升到外部作用域
                function mdToOrderedList(md) {
                    // 使用marked.js渲染Markdown
                    if (typeof marked !== 'undefined') {
                        try {
                            marked.setOptions({ breaks: true, gfm: true });
                            return marked.parse(md);
                        } catch (e) {
                            console.warn('Marked.js渲染失败，使用备用方法:', e);
                        }
                    }
                    // 备用方法：简单处理
                    const lines = md.split(/\r?\n/);
                    let inList = false;
                    let html = '';
                    let listBuffer = [];
                    for (let line of lines) {
                        if (/^([*\-•]|\d+[\.、])\s+/.test(line)) {
                            inList = true;
                            listBuffer.push(line.replace(/^([*\-•]|\d+[\.、])\s+/, ''));
                        } else {
                            if (inList) {
                                html += '<ol style="margin:0 0 0 22px;padding:0 0 0 8px;">' + listBuffer.map(item => `<li>${item}</li>`).join('') + '</ol>';
                                listBuffer = [];
                                inList = false;
                            }
                            html += line ? `<div>${line}</div>` : '<br>';
                        }
                    }
                    if (inList && listBuffer.length > 0) {
                        html += '<ol style="margin:0 0 0 22px;padding:0 0 0 8px;">' + listBuffer.map(item => `<li>${item}</li>`).join('') + '</ol>';
                    }
                    return html;
                }
                analysisDiv.innerHTML = beautifyAnalysisSections(result);
                // 对代码块进行语法高亮
                if (typeof hljs !== 'undefined') {
                    analysisDiv.querySelectorAll('pre code').forEach((block) => {
                        hljs.highlightElement(block);
                    });
                }
            } else {
                analysisDiv.innerHTML = '<span style="color:#e74c3c;">' + (data.message || '分析失败') + '</span>';
            }
        } catch (e) {
            analysisDiv.innerHTML = '<span style="color:#e74c3c;">分析出错: ' + e + '</span>';
        }
    };
    </script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const generateBtn = document.getElementById('generate-btn');
            const knowledgePointTags = document.querySelectorAll('.knowledge-point-tag');
            const difficultySelect = document.getElementById('difficulty');
            const questionContent = document.getElementById('question-content');
            const solutionContent = document.getElementById('solution-content');
            const solutionText = document.getElementById('solution-text');
            const viewSolutionBtn = document.getElementById('view-solution-btn');
            let currentSolution = null;

            knowledgePointTags.forEach(tag => {
                tag.addEventListener('click', () => {
                    tag.classList.toggle('selected');
                });
            });

            generateBtn.addEventListener('click', async function() {
                const selectedTags = document.querySelectorAll('.knowledge-point-tag.selected');
                const knowledgePoints = Array.from(selectedTags).map(tag => tag.innerText);
                const difficulty = difficultySelect.options[difficultySelect.selectedIndex].text;

                if (knowledgePoints.length === 0) {
                    alert('请至少选择一个知识点！');
                    return;
                }

                // 添加加载状态
                generateBtn.classList.add('loading');
                generateBtn.disabled = true;
                const originalText = generateBtn.innerHTML;
                generateBtn.innerHTML = '<i class="fas fa-spinner"></i> 正在生成...';

                questionContent.innerHTML = `<p>正在为知识点 \"${knowledgePoints.join(', ')}\" 和难度 \"${difficulty}\" 生成题目...</p>`;
                solutionContent.style.display = 'none';
                viewSolutionBtn.style.display = 'none';
                currentSolution = null;

                try {
                    const response = await fetch('/api/generate_question', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ knowledge_points: knowledgePoints, difficulty: difficulty }),
                    });

                    const data = await response.json();

                    if (data.status === 'success') {
                        const question = data.question;
                        questionContent.innerHTML = `<p>${question.question}</p>`;
                        // 确保 Monaco Editor 已初始化
                        if (monacoEditor) {
                            monacoEditor.setValue(question.code || '');
                        } else {
                            // 如果 Monaco Editor 还未初始化，等待初始化完成
                            setTimeout(() => {
                                if (monacoEditor) {
                                    monacoEditor.setValue(question.code || '');
                                }
                            }, 1000);
                        }
                        currentSolution = { answer: question.answer, explanation: question.explanation };
                        viewSolutionBtn.style.display = 'inline-block';
                    } else {
                        questionContent.innerHTML = `<p style="color: red;">题目生成失败: ${data.message}</p>`;
                    }
                } catch (error) {
                    questionContent.innerHTML = `<p style="color: red;">请求失败: ${error}</p>`;
                } finally {
                    // 移除加载状态
                    generateBtn.classList.remove('loading');
                    generateBtn.disabled = false;
                    generateBtn.innerHTML = originalText;
                }
            });

            viewSolutionBtn.addEventListener('click', function() {
                if (currentSolution) {
                    solutionText.innerHTML = `<strong>答案:</strong><pre><code class="language-rust">${currentSolution.answer}</code></pre><strong>解析:</strong><p>${currentSolution.explanation}</p>`;
                    solutionContent.style.display = 'block';
                    // Re-run highlight to style the new code block
                    if (typeof hljs !== 'undefined') {
                        document.querySelectorAll('pre code').forEach((block) => {
                            hljs.highlightElement(block);
                        });
                    }
                } else {
                    solutionText.innerHTML = '<p>没有可用的解析。</p>';
                    solutionContent.style.display = 'block';
                }
            });
        });
    </script>
</body>
</html>